<template>
  <div class="login-page">
    <!-- 头部 -->
    <div class="header">
      <div class="back" @click="$router.back()">
        <i class="iconfont icon-back"></i>
      </div>
      <div class="title">用户登录</div>
    </div>

    <!-- 登录表单 -->
    <div class="login-form">
      <div class="form-item">
        <label>手机号：</label>
        <input type="tel" v-model="form.userId" placeholder="请输入手机号">
      </div>
      <div class="form-item">
        <label>密码：</label>
        <input type="password" v-model="form.password" placeholder="请输入密码">
      </div>
    </div>

    <!-- 按钮区域 -->
    <div class="btn-group">
      <div class="login-btn" @click="login">登录</div>
      <div class="register-btn" @click="$router.push('/register')">去注册</div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'
import { useUserStore } from '../../stores/user'

const router = useRouter()
const route = useRoute()
const form = ref({
  userId: '',
  password: ''
})

const userStore = useUserStore()

// 登录
const login = async () => {
  // 表单验证
  if (!form.value.userId) {
    alert('请输入手机号')
    return
  }
  if (!form.value.password) {
    alert('请输入密码')
    return
  }

  try {
    const res = await axios.get('/user/getUserByIdByPass', {
      params: form.value
    })
    if (res.data) {
      // 使用Pinia存储用户信息
      userStore.setUserId(res.data.userId)
      if (route.query.redirect) {
        router.replace(route.query.redirect)
      } else {
        router.replace('/')
      }
    } else {
      alert('用户名或密码错误')
    }
  } catch (error) {
    console.error('登录失败:', error)
  }
}
</script>

<style scoped>
.login-page {
  padding-top: 44px;
  background: #f5f5f5;
  min-height: 100vh;
}

.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 44px;
  background: #0097ff;
  color: #fff;
  display: flex;
  align-items: center;
  padding: 0 15px;
  z-index: 100;
}

.back {
  padding: 10px;
  margin-left: -10px;
}

.title {
  flex: 1;
  text-align: center;
  font-size: 16px;
}

.login-form {
  background: #fff;
  margin-top: 20px;
}

.form-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.form-item label {
  width: 80px;
  color: #333;
}

.form-item input {
  flex: 1;
  border: none;
  outline: none;
  font-size: 14px;
}

.btn-group {
  padding: 20px 15px;
}

.login-btn {
  height: 44px;
  background: #0097ff;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 22px;
  font-size: 16px;
  margin-bottom: 15px;
}

.register-btn {
  height: 44px;
  background: #fff;
  color: #0097ff;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 22px;
  font-size: 16px;
  border: 1px solid #0097ff;
}
</style> 